# -*- coding: utf-8 -*-
# @Time    : 2018/6/7 下午10:42
# @Author  : Lavn
# @Email   : 959875529@qq.com
# @File    : ProcessDemo.py
# @Software: PyCharm


#多进程 demo
# import multiprocessing
# import time
#
#
# def worker(interval, name):
#     print(name + '【start】')
#     time.sleep(interval)
#     print(name + '【end】')
#
#
# if __name__ == "__main__":
#     p1 = multiprocessing.Process(target=worker, args=(2, '两点水1'))
#     p2 = multiprocessing.Process(target=worker, args=(3, '两点水2'))
#     p3 = multiprocessing.Process(target=worker, args=(4, '两点水3'))
#
#     p1.start()
#     p2.start()
#     p3.start()
#
#     print("The number of CPU is:" + str(multiprocessing.cpu_count()))
#     for p in multiprocessing.active_children():
#         print("child   p.name:" + p.name + "\tp.id" + str(p.pid))
#     print("END!!!!!!!!!!!!!!!!!")


# #把进程创建成类
# import multiprocessing
# import time
#
#
# class ClockProcess(multiprocessing.Process):
#     def __init__(self, interval):
#         multiprocessing.Process.__init__(self)
#         self.interval = interval
#
#     def run(self):
#         for i in range(5):
#             print("当前时间: {0} -- {1}".format(time.ctime(),i))
#             time.sleep(self.interval)
#
#
# if __name__ == '__main__':
#     p = ClockProcess(3)
#     p.start()


# import multiprocessing
# import time
#
#
# def worker(interval):
#     print('工作开始时间：{0}'.format(time.ctime()))
#     time.sleep(interval)
#     print('工作结果时间：{0}'.format(time.ctime()))
#
#
# if __name__ == '__main__':
#     p = multiprocessing.Process(target=worker, args=(3,))
#     p.start()
#     print('【EMD】')


import multiprocessing
import time


def worker(interval):
    print('工作开始时间：{0}'.format(time.ctime()))
    time.sleep(interval)
    print('工作结果时间：{0}'.format(time.ctime()))


if __name__ == '__main__':
    p = multiprocessing.Process(target=worker, args=(3,))
    p.daemon = True
    p.start()
    time.sleep(2)
    print('【EMD】')
#主进程结束 子进程都结束 daemon子进程设置daemon属性


#join 方法 子进程走完 在走主
# import multiprocessing
# import time
#
#
# def worker(interval):
#     print('工作开始时间：{0}'.format(time.ctime()))
#     time.sleep(interval)
#     print('工作结果时间：{0}'.format(time.ctime()))
#
#
# if __name__ == '__main__':
#     p = multiprocessing.Process(target=worker, args=(3,))
#     p.daemon = True
#     p.start()
#     p.join()
#     print('【EMD】')

# Pool
#如果需要很多的子进程，难道我们需要一个一个的去创建吗？
#当然不用，我们可以使用进程池的方法批量创建子进程。

from multiprocessing import Pool
import os, time, random


def long_time_task(name):
    print('进程的名称：{0} ；进程的PID: {1} '.format(name, os.getpid()))
    start = time.time()
    time.sleep(random.random() * 3)
    end = time.time()
    print('进程 {0} 运行了 {1} 秒'.format(name, (end - start)))


if __name__ == '__main__':
    print('主进程的 PID：{0}'.format(os.getpid()))
    p = Pool(6)
    for i in range(6):
        p.apply_async(long_time_task, args=(i,))
    p.close()
    # 等待所有子进程结束后在关闭主进程
    p.join()
    print('【End】')

"""
哈哈
"""



